/*******************************************************************************
 *
 * Copyright (c) 2008-2011 ayound@gmail.com, guwei8576431@gmail.com
 * This program and the accompanying materials
 * are made available under the terms of the GNU GENERAL PUBLIC LICENSE
 * which accompanies this distribution, and is available at
 * http://dev.perl.org/licenses/gpl1.html
 * All rights reserved.
 *
 * Created on 2009-10-25
 *******************************************************************************/

package org.cgtw.scriptprofile.server.manager;

import java.awt.print.Book;
import java.util.Iterator;

import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.cgtw.scriptprofile.engine.compile.FunctionInfo;
import org.cgtw.scriptprofile.engine.compile.IScriptCompileEngine;
import org.cgtw.scriptprofile.engine.manager.ScriptCompileManager;
import org.cgtw.scriptprofile.server.model.ProfileData;
import org.cgtw.scriptprofile.server.model.ProfileItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class ProfileParamsTranslator {

	private String jsonString;

	public ProfileParamsTranslator(String jsonString) {
		this.jsonString = jsonString;
	}

	public void translator() throws JSONException {
		JSONObject jsonObject = new JSONObject(new JSONTokener(jsonString));
		JSONArray items = jsonObject.getJSONArray("items");
		IScriptCompileEngine engine = ScriptCompileManager.getInstance()
				.getScriptCompileEngine();
		for (int i = 0; i < items.length(); i++) {
			JSONArray item = items.getJSONArray(i);
			int execIndex = item.getInt(0);
			int funcIndex = item.getInt(1);
			long start = item.getLong(2);
			long end = item.getLong(3);
			FunctionInfo info = engine.getFunctionInfo(funcIndex);
			ProfileItem pItem = new ProfileItem();
			pItem.setExecIndex(execIndex);
			pItem.setFuncIndex(funcIndex);
			pItem.setFuncName(info.getName());
			pItem.setLine(info.getLine());
			pItem.setUrl(info.getUrl());
			pItem.setStart(start);
			pItem.setEnd(end);
			pItem.setTime(end - start);
			ProfileData.addProfileItem(execIndex, pItem);
		}
		JSONObject relation = jsonObject.getJSONObject("relation");
		Iterator it = relation.keys();
		while (it.hasNext()) {
			Object key = it.next();
			JSONArray currRelation = relation.getJSONArray(key.toString());
			Integer[] currRelations = new Integer[currRelation.length()];
			for (int i = 0; i < currRelation.length(); i++) {
				currRelations[i] = currRelation.getInt(i);
			}
			ProfileData.setRelation(Integer.valueOf(key.toString()),
					currRelations);
		}
		JSONArray root = jsonObject.getJSONArray("root");
		Integer[] rootIndex = new Integer[root.length()];
		for (int i = 0; i < root.length(); i++) {
			rootIndex[i] = root.getInt(i);
		}
		ProfileData.setRootIndex(rootIndex);
	}

}
